package com.qny.ai.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.imageio.ImageIO;

@Slf4j
@Component
public class AvatarGenerator {

    private static final int AVATAR_SIZE = 200;
    private static final Random random = new Random();
    
    // 角色类别对应的颜色方案
    private static final Map<String, Color[]> CATEGORY_COLORS = new HashMap<>();
    
    static {
        // 助手类 - 蓝色系
        CATEGORY_COLORS.put("assistant", new Color[]{
            new Color(59, 130, 246), new Color(37, 99, 235), new Color(29, 78, 216)
        });
        
        // 娱乐类 - 紫色系
        CATEGORY_COLORS.put("entertainment", new Color[]{
            new Color(147, 51, 234), new Color(126, 34, 206), new Color(109, 40, 217)
        });
        
        // 教育类 - 绿色系
        CATEGORY_COLORS.put("education", new Color[]{
            new Color(34, 197, 94), new Color(22, 163, 74), new Color(21, 128, 61)
        });
        
        // 商务类 - 灰色系
        CATEGORY_COLORS.put("business", new Color[]{
            new Color(107, 114, 128), new Color(75, 85, 99), new Color(55, 65, 81)
        });
        
        // 创作类 - 橙色系
        CATEGORY_COLORS.put("creative", new Color[]{
            new Color(249, 115, 22), new Color(234, 88, 12), new Color(194, 65, 12)
        });
        
        // 生活类 - 粉色系
        CATEGORY_COLORS.put("life", new Color[]{
            new Color(236, 72, 153), new Color(219, 39, 119), new Color(190, 24, 93)
        });
    }
    
    /**
     * 生成角色头像
     * @param roleName 角色名称
     * @param category 角色类别
     * @return Base64编码的头像图片
     */
    public String generateAvatar(String roleName, String category) {
        try {
            BufferedImage image = new BufferedImage(AVATAR_SIZE, AVATAR_SIZE, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = image.createGraphics();
            
            // 设置抗锯齿
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            
            // 获取类别对应的颜色
            Color[] colors = CATEGORY_COLORS.getOrDefault(category, CATEGORY_COLORS.get("assistant"));
            
            // 生成渐变背景
            GradientPaint gradient = new GradientPaint(
                0, 0, colors[0],
                AVATAR_SIZE, AVATAR_SIZE, colors[1]
            );
            g2d.setPaint(gradient);
            g2d.fillRoundRect(0, 0, AVATAR_SIZE, AVATAR_SIZE, 20, 20);
            
            // 添加装饰性圆形
            g2d.setColor(new Color(255, 255, 255, 30));
            g2d.fillOval(20, 20, 60, 60);
            g2d.fillOval(120, 120, 40, 40);
            
            // 绘制角色名称的首字母
            String firstChar = roleName.substring(0, 1).toUpperCase();
            g2d.setColor(Color.WHITE);
            g2d.setFont(new Font("Microsoft YaHei", Font.BOLD, 80));
            
            FontMetrics fm = g2d.getFontMetrics();
            int x = (AVATAR_SIZE - fm.stringWidth(firstChar)) / 2;
            int y = (AVATAR_SIZE - fm.getHeight()) / 2 + fm.getAscent();
            
            g2d.drawString(firstChar, x, y);
            
            // 添加小图标
            drawCategoryIcon(g2d, category, colors[2]);
            
            g2d.dispose();
            
            // 转换为Base64
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "PNG", baos);
            byte[] imageBytes = baos.toByteArray();
            
            return Base64.getEncoder().encodeToString(imageBytes);
            
        } catch (IOException e) {
            log.error("生成头像失败: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 绘制类别图标
     */
    private void drawCategoryIcon(Graphics2D g2d, String category, Color iconColor) {
        g2d.setColor(new Color(iconColor.getRed(), iconColor.getGreen(), iconColor.getBlue(), 100));
        g2d.setFont(new Font("Arial", Font.PLAIN, 24));
        
        String icon = getCategoryIcon(category);
        FontMetrics fm = g2d.getFontMetrics();
        int x = AVATAR_SIZE - 30 - fm.stringWidth(icon);
        int y = 30;
        
        g2d.drawString(icon, x, y);
    }
    
    /**
     * 获取类别对应的图标
     */
    private String getCategoryIcon(String category) {
        switch (category) {
            case "assistant": return "🤖";
            case "entertainment": return "🎭";
            case "education": return "📚";
            case "business": return "💼";
            case "creative": return "🎨";
            case "life": return "🏠";
            default: return "🌟";
        }
    }
    
    /**
     * 生成随机头像（用于测试）
     */
    public String generateRandomAvatar(String roleName) {
        String[] categories = {"assistant", "entertainment", "education", "business", "creative", "life"};
        String randomCategory = categories[random.nextInt(categories.length)];
        return generateAvatar(roleName, randomCategory);
    }
}
